package com.ikunikun.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.aliyuncs.utils.StringUtils;
import com.ikunikun.constant.JwtClaimsConstant;
import com.ikunikun.constant.MessageConstant;
import com.ikunikun.dto.UserLoginDTO;
import com.ikunikun.entity.User;
import com.ikunikun.exception.LoginFailedException;
import com.ikunikun.mapper.UserMapper;
import com.ikunikun.properties.JwtProperties;
import com.ikunikun.properties.WeChatProperties;
import com.ikunikun.service.UserService;
import com.ikunikun.utils.HttpClientUtil;
import com.ikunikun.utils.JwtUtil;
import com.ikunikun.vo.UserLoginVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {

	private final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

	@Resource
	private WeChatProperties weChatProperties;
	@Resource
	private JwtProperties jwtProperties;
	@Resource
	private UserMapper userMapper;

	/**
	 * 微信登录
	 * @param userLoginDTO
	 * @return
	 */
	@Override
	public UserLoginVO login(UserLoginDTO userLoginDTO) {
		// 获取openid
		String openid = this.getOpenid(userLoginDTO.getCode());

		// 判断当前用户是否为新用户
		User user = userMapper.getByOpenid(openid);
		if (Objects.isNull(user)){
			// 若为新用户，自动完成注册
			// TODO 用户其他信息注入
			user = User.builder()
					.openid(openid)
					.createTime(LocalDateTime.now())
					.build();
			userMapper.insert(user);
		}

		Map<String, Object> claims = new HashMap<>();
		claims.put(JwtClaimsConstant.USER_ID, user.getId());
		claims.put("openid", openid);

		String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

		UserLoginVO userLoginVO = UserLoginVO.builder()
				.id(user.getId())
				.openid(openid)
				.token(token)
				.build();
		return userLoginVO;
	}

	/**
	 * 调用微信登录接口
	 * @param code
	 * @return
	 */
	private String getOpenid(String code) {
		// 调用微信接口服务
		HashMap<String, String> map = new HashMap<>();
		map.put("appid", weChatProperties.getAppid());
		map.put("secret", weChatProperties.getSecret());
		map.put("js_code", code);
		map.put("grant_type", "authorization_code");
		String json = HttpClientUtil.doGet(this.WX_LOGIN, map);
		JSONObject parse = JSON.parseObject(json);
		String openid = parse.getString("openid");
		// 判断openid是否为空，为空表示登录失败
		if (StringUtils.isEmpty(openid)){
			throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
		}
		return openid;
	}
}
